package com.jiedeng.controller;

import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 覃远龙
 * @ClassName: AdminController
 * @Description:
 * @date 2017/5/24 14:03
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    ISysAdministratorRepository sysAdministratorRepository;

    @Autowired
    IAppVersionRepository appVersionRepository;

    @Autowired
    IPersonRepository personRepository;

    @Autowired
    ISysModuleRepository sysModuleRepository;

    @Autowired
    ISysRuleRepository ruleRepository;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String CreateAdmin(@RequestBody SysAdministrator administrator, HttpSession session) throws Exception{
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(administrator.getLoginPwd().getBytes());
        String pwd = new BigInteger(1, messageDigest.digest()).toString(16);
        administrator.setLoginPwd(pwd);
        administrator.setTs((new Date()));

        sysAdministratorRepository.save(administrator);

        return "OK";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String Login(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpSession session){

        List<SysAdministrator> sysAdministrator = sysAdministratorRepository.findByLoginIdAndLoginPwdAndCorpId(map.get("userName").toString(), map.get("password").toString(), Long.parseLong(map.get("corpId").toString()));
        if(sysAdministrator == null || sysAdministrator.size() < 1){
            return "User not exist";
        }
        session.setAttribute("userName", map.get("userName").toString());
        return "OK";
    }

    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public Map<String, Object> Signin(String loginid, String password){
        List<Person> people = personRepository.findByLoginidAndPassword(loginid, password);
        Map<String, Object> rst = new HashMap<String, Object>();
        if(people == null || people.size() == 0){
            rst.put("code", 2);
            rst.put("message", "user not exist, or password wrong");
            return rst;
        }

        Person person = people.get(0);
        if(person.isLock()){
            rst.put("code", 3);
            rst.put("message", "user lock");
            return rst;
        }

        Calendar cal = Calendar.getInstance();
        long curTime = cal.getTime().getTime();
        long start = person.getStartTime().getTime();
        long end = person.getEndTime().getTime();
        if(curTime - start < 0 || curTime - end > 0){
            rst.put("code", 4);
            rst.put("message", "out of start or end time");
            return  rst;
        }

        rst.put("code", 1);
        rst.put("message", "OK");
        rst.put("userInfo", person);
        return  rst;
    }

    @ResponseBody
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public String upload(@RequestParam MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 这里只是简单例子，文件直接输出到项目路径下。
                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
                // 还有关于文件格式限制、文件大小限制，详见：中配置。
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File("C://upload//" + getFormatDate() + ".pdf")));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "failed," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "failed," + e.getMessage();
            }
            return "success";
        } else {
            return "failed，file is empty.";
        }
    }

    public String getFormatDate(){
        Date date = new Date();
        long times = date.getTime();//时间戳
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(date);
        return dateString;
    }

    @ResponseBody
    @RequestMapping(value="/checkUpdate", method = RequestMethod.GET)
    @ApiOperation(value = "检查更新")
    public AppVersion checkUpdate(String versionName){
        List<AppVersion> appVersions = appVersionRepository.findByVersionName(versionName);
        AppVersion appVersion;
        if(appVersions!=null && appVersions.size() > 0){
            appVersion = appVersions.get(0);
            appVersions = appVersionRepository.findTop1ByCreateTimeGreaterThanAndOpenOrderByCreateTimeDesc(appVersion.getCreateTime(), appVersion.getOpen());
        }else {
            return  null;
        }

        if(appVersions!=null && appVersions.size() > 0){
            return appVersions.get(0);
        }else{
            return null;
        }
    }

    @ResponseBody
    @RequestMapping(value="/modules" , method = RequestMethod.GET)
    @ApiOperation(value = "getSysModule")
    public List<SysModule> getSysModule(){
        return sysModuleRepository.findAll();
    }

    @ResponseBody
    @RequestMapping(value="/rules", method = RequestMethod.GET)
    @ApiOperation(value = "getSysRules")
    public List<SysRule> getSysRules(){
        return ruleRepository.findAll();
    }

}
